<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableList"
        highlight-current-row
        border
        class="data-table__content"
      >
        <el-table-column label="合同名称" prop="contractName" min-width="200" />
        <el-table-column label="负责人" prop="majorUsername" />
        <el-table-column label="状态" prop="status" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.status" type="success">
              {{ ContractBuild_Status_Label[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="派单时间" prop="dispatchTime" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              @click="showWindow(scope.row)"
              type="primary"
              size="small"
              link
              icon="edit"
              v-if="!scope.row.dispatchTime"
            >
              派单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 弹窗：关联人员 -->
    <el-dialog
      v-model="dialog.visible"
      v-loading="dialog.loading"
      :title="dialog.title"
      width="580px"
      @close="closeWindow"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="合同名称" prop="name">
          {{ curBuild?.contractName }}
        </el-form-item>
        <el-form-item label="负责人" prop="majorUserId">
          <el-select v-model="formData.majorUserId" search placeholder="请选择">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
              :disabled="formData.userIds?.includes(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参与人" prop="userIds">
          <el-select v-model="formData.userIds" multiple search placeholder="请选择">
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
              :disabled="formData.majorUserId == item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="closeWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import BuildAPI, { BuildForm, BuildPageVO, ContractBuild_Status_Label } from "@/api/flow/build.api";
import UserAPI, { UserPageVO } from "@/api/system/user.api";
import { cloneDeep } from "lodash-es";

defineOptions({
  name: "BuildDispatch",
  inheritAttrs: false,
});

const roleFormRef = ref();
const queryFormRef = ref();

const loading = ref(false);
const total = ref(0);
const curBuild = ref<BuildPageVO>();
const queryParams = reactive<PageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const defaultFormData = {
  contractId: "",
  majorUserId: "",
  userIds: [],
};
const tableList = ref<BuildPageVO[]>();
const formData = reactive<BuildForm>(cloneDeep(defaultFormData));
const rules = reactive({
  majorUserId: [{ required: true, message: "请选择负责人", trigger: "blur" }],
  userIds: [{ required: true, message: "请选择参与人", trigger: "blur" }],
});
const userOptions = ref<UserPageVO[]>([]); // 用户列表

// 弹窗
const dialog = reactive({
  title: "选择人员",
  visible: false,
  loading: false,
});

onMounted(() => {
  handleQuery();
  UserAPI.getOptions().then((data) => {
    userOptions.value = data;
  });
});

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 获取数据
function fetchData() {
  loading.value = true;
  BuildAPI.getPage(queryParams)
    .then((data) => {
      tableList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 关闭弹窗
 */
function closeWindow() {
  dialog.visible = false;
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
}
/**
 * 打开弹窗
 */
function showWindow(row: BuildPageVO) {
  dialog.visible = true;
  curBuild.value = row;
}

/**
 * 提交分派
 */
function submit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const sendData = { ...formData, contractId: curBuild.value?.contractId || "" };
      BuildAPI.dispatch(sendData)
        .then(() => {
          ElMessage.success("分派成功");
          closeWindow();
          fetchData();
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>
